package com.chey.service.impl;

import com.chey.domain.Permission;
import com.chey.domain.User;
import com.chey.domain.UserSecurity;
import com.chey.service.PermissionService;
import com.chey.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService service;
    @Autowired
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        User user=service.searchByName(username);
        //判断
        if(user!=null){
            System.out.println(username);
            //定义一个set集合，用户存放授权（角色和权限）
            Set<GrantedAuthority> authoritySet=new HashSet<>();
            //从数据库中获取权限集合信息
            List<Permission> list=permissionService.searchByUserId(user.getId());
            System.out.println(list);
            //循环封装
            for (Permission permission:list) {
                authoritySet.add(new SimpleGrantedAuthority(permission.getUrl()));
            }

            //封装
            UserSecurity userSecurity=new UserSecurity(user,authoritySet);

            return userSecurity;
        }
        return null;
    }
}
